package com.jhw.ymcc.service.impl;

import   com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jhw.ymcc.constants.RedisSmsConstants;
import com.jhw.ymcc.domain.*;
import com.jhw.ymcc.dto.RedisSmsDto;
import com.jhw.ymcc.dto.RegisterDto;
import com.jhw.ymcc.exception.GlobalErrorCode;
import com.jhw.ymcc.feign.LoginService;
import com.jhw.ymcc.mapper.UserMapper;
import com.jhw.ymcc.result.JSONResult;
import com.jhw.ymcc.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jhw.ymcc.util.AssertUtil;
import com.jhw.ymcc.util.BitStatesUtils;
import com.jhw.ymcc.util.QRCodeUtil;
import com.jhw.ymcc.util.StrUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author jhw
 * @since 2022-09-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private IUserBaseInfoService userBaseInfoService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private IUserCodeService userCodeService;

    @Autowired
    private IUserIntegralService userIntegralService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void smsRegister(RegisterDto smsRegisterDto) {

        String mobile = smsRegisterDto.getMobile();
        Integer regChannel = smsRegisterDto.getRegChannel();
        String smsCode = smsRegisterDto.getSmsCode();
        String code = smsRegisterDto.getCode();
        // 1.已用JSR3完成校验
        // 2.拼接业务键 去redis去获取短信验证码 检验短信验证码在redis中是否过期
        String key = String.format(RedisSmsConstants.REDIS_REGISTER_PHONE_KEY, mobile);
        Object o = redisTemplate.opsForValue().get(key);
        // 判断是否为空 为空代表已经过期
        AssertUtil.isNotNull(o, GlobalErrorCode.CODE_IS_NULL_ERROR);
        // 判断短信验证码是否正确
        RedisSmsDto redisSmsDto = (RedisSmsDto) o;
        AssertUtil.isEquals(smsCode, redisSmsDto.getCode(), GlobalErrorCode.CODE_ERROR);
        // 根据手机号查询用户信息
        User user = selectUser(mobile);
        // 判断用户是否已经存在
        AssertUtil.isNull(user, GlobalErrorCode.USER_EXISTED_ERROR);
        // 保存login
        JSONResult jsonResult = saveLogin(smsRegisterDto);
        // 断言Jsonresult是否成功
        AssertUtil.isTrue(jsonResult.isSuccess(), GlobalErrorCode.USER_SAVE_ERROR);
        // 断言ID是否为空
        AssertUtil.isNotNull(jsonResult.getData(), GlobalErrorCode.USER_SAVE_ERROR);
        // 获取ID
        Long loginId = Long.valueOf(jsonResult.getData().toString());
        // 保存user相关表
        // 保存用户信息
        Long userId = saveUser(loginId, smsRegisterDto);
        // 保存用户基本信息
        saveUserAccount(userId);
        // 获取推荐人id
        Long referId = checkReferCode(code);
        // 7.1 给新用户生成随机的推荐码
        saveUserCode(userId);
        // 8.保存t_user_base_info
        saveUserBaseInfo(smsRegisterDto.getRegChannel(),userId,referId);
        // 9.给推荐人赠送积分和成长值
        if (referId != null) {
            userIntegralService.integralFromRegister(referId);
            userBaseInfoService.growScoreFromRegister(referId);
        }
    }

    private void saveUserCode(Long userId) {
        UserCode userCode = new UserCode();
        userCode.setUserId(userId);
        userCode.setState(UserCode.CODE_NOT_USED);
        String code = StrUtils.getComplexRandomString(4);
        userCode.setCode(code);
        String url = null;
        try {
            url = "http://127.0.0.1:6003/reg.phone.html?code=" + code;
            // 生成的二维码的路径及名称
            String destPath = "E:\\software\\IdeaWorkSpace\\pps-ppscc\\ppscc-ui\\ppscc-ui-user\\img\\qrIMG\\"+code+".JPG";
            //生成二维码
            QRCodeUtil.encode(url,null,destPath, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        userCode.setQrUrl(url);
        userCodeService.insert(userCode);
    }

    private Long checkReferCode(String code) {
        if (!StringUtils.isEmpty(code)) {
            EntityWrapper<UserCode> wrapper = new EntityWrapper<>();
            wrapper.eq("code",code);
            wrapper.eq("state",UserCode.CODE_NOT_USED);
            UserCode userCode = userCodeService.selectOne(wrapper);
            Long referId = userCode.getUserId();
            AssertUtil.isNotNull(userCode,GlobalErrorCode.REFER_CODE_ERROR);
            userCode.setState(UserCode.CODE_USED);
            EntityWrapper<UserCode> wrapper1 = new EntityWrapper<>();
            wrapper1.eq("user_id",referId);
            userCodeService.update(userCode,wrapper1);
            return referId;
        }
        return null;
    }

    private void saveUserAccount(Long userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setCreateTime(new Date().getTime());
        userAccount.setPassword("123456");
        userAccount.setId(userId);
        userAccount.setUsableAmount(new BigDecimal(0));
        userAccount.setFrozenAmount(new BigDecimal(0));
        userAccountService.insert(userAccount);
    }

    private void saveUserBaseInfo(Integer regChannel,Long userId,Long referId) {
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(userId);
        userBaseInfo.setCreateTime(System.currentTimeMillis());
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfo.setReferId(referId);
        userBaseInfoService.insert(userBaseInfo);
    }

    private Long saveUser(Long loginId, RegisterDto smsRegisterDto) {
        User user = new User();
        user.setCreateTime(new Date().getTime());
        user.setLoginId(loginId);
        user.setNickName(smsRegisterDto.getMobile());
        user.setPhone(smsRegisterDto.getMobile());
        long bitStatetmp = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        long bitstate = BitStatesUtils.addState(bitStatetmp, BitStatesUtils.OP_AUTHED_PHONE);
        user.setBitState(bitstate);
        insert(user);
        return user.getId();
    }

    // 保存login
    private JSONResult saveLogin(RegisterDto smsRegisterDto) {
        Login login = new Login();
        login.setUsername(smsRegisterDto.getMobile());
        login.setPassword(smsRegisterDto.getPassword());
        login.setType(Login.USER_TYPE);
        login.setEnabled(Login.ENABLE);
        return loginService.saveOrUpdate(login);
    }
    // 根据手机号查询用户信息
    private User selectUser(String mobile) {
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("phone", mobile);
        return selectOne(wrapper);
    }
}
